﻿using System;
using System.Windows;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Threading;
using System.Windows.Input;

namespace FileRenamer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindow"/> class.
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Add Log Line
        /// </summary>
        /// <param name="Message">The message.</param>
        private void AddLog(String Message)
        {
            this.TextBoxLog.Text = DateTime.Now.ToString("hh:mmm:ss - ") + Message + "\r\n" + this.TextBoxLog.Text;
            System.Windows.Forms.Application.DoEvents();
        }
        /// <summary>
        /// Rename File
        /// </summary>
        /// <param name="Source">The source.</param>
        /// <param name="Destination">The destination.</param>
        private void FileRenamer(string Source, string Destination)
        {
            /// Primary Return Condition
            if (string.IsNullOrEmpty(Source)) return;
            if (string.IsNullOrEmpty(Destination)) return;

            /// Rename File
            try
            {
                Source = Path.Combine(this.TextBoxFolder.Text, Source);
                Destination = Path.Combine(this.TextBoxFolder.Text, Destination);
                File.Move(Source, Destination);
                this.AddLog(String.Format("Rename {0} to {1} was successfully finished.", Source, Destination));
            }
            catch (Exception ex)
            {
                this.AddLog(String.Format("Rename {0} to {1} was failed :-( because: {2}", Source, Destination, ex.Message));
            }

        }
        /// <summary>
        /// Releases the object.
        /// </summary>
        /// <param name="Object">The object.</param>
        private void ReleaseObject(object Object)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(Object);
                Object = null;
            }
            catch (Exception ex)
            {
                Object = null;
                MessageBox.Show("Oops! Unable to release the Object:\r\n" + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }
        /// <summary>
        /// Safe Conversion to String
        /// </summary>
        /// <param name="Value">The value.</param>
        /// <returns></returns>
        private string ConvertToString(dynamic Value)
        {
            try { return Convert.ToString(Value); }
            catch { return null; }
        }


        /// <summary>
        /// Handles the Click event of the ButtonRun control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
        private void ButtonRun_Click(object sender, RoutedEventArgs e)
        {
            /// File Check
            if (string.IsNullOrEmpty(this.TextBoxExcel.Text))
            {
                MessageBox.Show("Please fill the excel filename", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            /// Run Looop
            try
            {
                this.Cursor = Cursors.Wait;

                /// Read Excel
                Excel.Application ExcelApp = new Excel.Application();
                Excel.Workbook ExcelWorkbook = ExcelApp.Workbooks.Open(this.TextBoxExcel.Text, 0, true, Type.Missing, "", "", true, Type.Missing, Type.Missing, false, false, 0, true, 1, 0);
                Excel.Worksheet ExcelWorksheet = (Excel.Worksheet)ExcelWorkbook.Worksheets.get_Item(1);

                /// Read File
                int RowIndex = 1;
                while (true)
                {
                    string Source = this.ConvertToString((ExcelWorksheet.Cells[RowIndex, 1] as Excel.Range).Value2);
                    if (string.IsNullOrEmpty(Source)) break;
                    string Destination = this.ConvertToString((ExcelWorksheet.Cells[RowIndex, 2] as Excel.Range).Value2);
                    this.FileRenamer(Source, Destination);
                    RowIndex++;
                }

                /// Close Excel
                ExcelWorkbook.Close(true, Type.Missing, Type.Missing);
                ExcelApp.Quit();

                /// Release Memory
                this.ReleaseObject(ExcelWorksheet);
                this.ReleaseObject(ExcelWorkbook);
                this.ReleaseObject(ExcelApp);

                /// Warning Message
                if (RowIndex == 1)
                {
                    MessageBox.Show("You need to have an excel file with a sheet and two first columns in TEXT format included valid filenames.", "Empty Excel Sheet !!!", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                this.Cursor = null;
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            this.Cursor = null;

        }
        /// <summary>
        /// Handles the Click event of the ButtonFolderBrowse control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
        private void ButtonFolderBrowse_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog FolderDialog = new System.Windows.Forms.FolderBrowserDialog();
            FolderDialog.SelectedPath = this.TextBoxFolder.Text;
            FolderDialog.Description = "Select the root folder";
            if (FolderDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
            this.TextBoxFolder.Text = FolderDialog.SelectedPath;
        }
        /// <summary>
        /// Handles the Click event of the ButtonExcelFileBrowse control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
        private void ButtonExcelFileBrowse_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog OpenDialog = new System.Windows.Forms.OpenFileDialog();
            OpenDialog.DefaultExt = ".xlsx";
            OpenDialog.Title = "Select Excel Files";
            OpenDialog.Filter = "Excel Files (*.xls;*.xlsx)|*.xls;*.xlsx|All Files...|*.*";
            if (OpenDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
            this.TextBoxExcel.Text = OpenDialog.FileName;
        }
    }
}
